package ru.spbau.bytecode.graph;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class CompositeVertex extends Vertex {
	
	private final List<Vertex> innerVertices = new LinkedList<Vertex>();
	
	private final Color color = new Color(255, 211, 155);
	
	public CompositeVertex(String name) {
		super(name);
	}

	public void addInnerVertex(Vertex v) {
		if (!innerVertices.contains(v)) {
			if (this.equals(v)) {
//				System.err.println(this.getName() + " " + v.getName());
				throw new IllegalStateException("Vertex shouldn't contain itself");
			}
			innerVertices.add(v);
		}
	}
	
	public void moveVertexToTop(Vertex v) {
		innerVertices.remove(v);
		innerVertices.add(v);
	}
	
	public boolean containsInnerVertex(Vertex v) {
		return innerVertices.contains(v);
	}
	
	public List<Vertex> getInnerVertices() {
		return Collections.unmodifiableList(innerVertices);
	}
	

	@Override
	public void move(int dx, int dy) {
		if (location.x + dx < bounds.x) {
			dx = bounds.x - location.x;
		}
		if (location.y + dy < bounds.y) {
			dy = bounds.y - location.y;
		}
		if (location.x + dx > bounds.x + bounds.width) {
			dx = bounds.x + bounds.width - location.x;
		}
		if (location.y + dy > bounds.y + bounds.height) {
			dy = bounds.y + bounds.height - location.y;
		}
		
		location.x += dx;
		location.y += dy;
		
		for (Vertex v: innerVertices) {
			v.setBounds(new Rectangle(location.x, location.y,
					size.width, size.height));
			v.move(dx, dy);
		}
	}

	@Override
	public void setCatched(boolean catched) {
		this.catched = catched;
		for (Vertex v: innerVertices) {
			v.setCatched(catched);
		}
	}
	
	@Override
	public void invert() {
		visible = !visible;
		
		for (Vertex v: innerVertices) {
			if (v.isVisible() != visible) {
				v.invert();
			}
		}
	}
	
	@Override
	public void draw(Graphics g) {
		if (visible) {
//			if (innerVertices.isEmpty()) {
				Color currentColor = g.getColor();
				//g.setColor(new Color(238, 238, 238));
				g.setColor(color);
				g.fillRect(location.x, location.y, size.width, size.height);
				g.setColor(currentColor);
//			}
			g.drawString(getName(), location.x + 5, location.y + 15);
			g.drawRect(location.x, location.y, size.width, size.height);
		}
		
		for (Vertex v: innerVertices) {
			v.draw(g);
		}
	}

}
